package Dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
//封装JDBC对数据库的操作
import java.util.List;

import org.apache.catalina.User;

public class UserDao {
	public static final String JDBC_URL="jdbc:mysql://localhost:3306/LoginTools?userUnicode=ture&characterEncoding=UTF-8&serverTimezone=UTC&allowMultiQueries=ture";
	public static final String JDBC_USER="localhost";
	public static final String JDBC_PASSWORD="123456";
	public void save(User user) {};
	public void delete(int id) {};
	public void update(User user) {};
	public User findById(int id) {
		public static void main(String args) {
			try {
				UserDAO userDAO = new UserDAO();
				System.out.println("查询id为2的用户信息");
				User user = userDAO.findById(2);
				System.out.println(user);
				System.out.println("查询所有的用户信息");
				List<User> userList = userDAO.findAll();
				for(User temp : userList) {
					System.out.println(temp);
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	public List<User> findAll(User user) throws Exception {
		List<User> userList = new ArrayList<User>();
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			con = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
			ps = con.prepareStatement("select * from users");
			ps.executeQuery();
			while(rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				userList.add(user);
			}
		}catch(Exception e){
			throw new Exception("数据库异常:" + e.getMessage());
		}finally {
			if(rs != null) {
				rs.close();
			}
			if(ps != null) {
				ps.close();
			}
			if(con != null) {
				con.close();
			}
		}
		return userList;
	}
}
